using System;
using System.Globalization;
using System.Text;
using BizTalk.BuildGenerator.MetaData;
using BizTalk.BuildGenerator.MetaData.ResourceAdapters;

namespace BizTalk.BuildGenerator.BuildFrameworks.Default.CommandBuilders
{
    public class RemoveFromGacCommandBuilder : ICommandBuilder
    {
        private const string CommandTag = "<!-- @RemoveFromGacCommand@ -->";

        private const string RemoveFromGacFormat =
            "\t\t<Exec Command='\"$(GacUtilPath)gacutil\" /u {0}' ContinueOnError=\"true\"/>";

        #region ICommandBuilder Members

        /// <summary>
        /// Adds the command to the file builder
        /// </summary>
        /// <param name="args"></param>
        /// <param name="fileBuilder"></param>
        public void Build(GenerationArgs args, StringBuilder fileBuilder)
        {
            var commandBuilder = new StringBuilder();

            foreach (var resource in args.ApplicationDescription.Resources)
            {
                switch (resource.Type)
                {
                    case ResourceTypes.Assembly:
                        {
                            var assemblyAdapter = AssemblyResourceAdapter.Create(resource);
                            commandBuilder.Append(
                                string.Format(CultureInfo.InvariantCulture, RemoveFromGacFormat,
                                              assemblyAdapter.AssemblyNameWithoutExtension));
                            commandBuilder.Append(Environment.NewLine);
                        }
                        break;
                    case ResourceTypes.BizTalkAssembly:
                        {
                            var btsAdapter = BizTalkAssemblyResourceAdapter.Create(resource);
                            commandBuilder.Append(
                                string.Format(CultureInfo.InvariantCulture, RemoveFromGacFormat,
                                              btsAdapter.AssemblyNameWithoutExtension));
                            commandBuilder.Append(Environment.NewLine);
                        }
                        break;
                }
            }

            fileBuilder.Replace(CommandTag, commandBuilder.ToString());
        }

        #endregion
    }
}